Search insert position

Time: O(LogN); Space: O(1); medium

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume NO duplicates in the array.

Example 1:

Input: nums = [1,3,5,6], target = 5

Output: 2

Example 2:

Input: nums = [1,3,5,6], target = 2

Output: 1

Example 3:

Input: nums = [1,3,5,6], target = 7

Output: 4

Example 4:

Input: nums = [1,3,5,6], target = 0

Output: 0

1. Binary Search [O(LogN),O(1)]

[1]:
class Solution1(object):
    """
    Time: O(LogN)
    Space: O(1)
    """
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left, right = 0, len(nums) - 1

        while left <= right:
            mid = left + (right - left) // 2
            if nums[mid] >= target:
                right = mid - 1
            else:
                left = mid + 1

        return left
[2]:
s = Solution1()

nums = [1,3,5,6]
target = 5
assert s.searchInsert(nums, target) == 2

nums = [1,3,5,6]
target = 2
assert s.searchInsert(nums, target) == 1

nums = [1,3,5,6]
target = 7
assert s.searchInsert(nums, target) == 4

nums = [1,3,5,6]
target = 0
assert s.searchInsert(nums, target) == 0